package mail.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.mail.internet.MimeUtility;

import sun.misc.BASE64Decoder;

public class StringUtil {
  public static String getFileName(String str) {
    if(str == null || str.length() == 0) {
      return str;
    }
    if(str.startsWith("=?GB2312") || str.startsWith("=?gb2312")) {
      BASE64Decoder decoder = new BASE64Decoder();
      try {
        return new String(decoder.decodeBuffer(str.substring(11, str.length()-2)), "GBK");
      } catch (IOException e) {
        e.printStackTrace();
        return str;
      }
    }else if(str.startsWith("=?GBK") || str.startsWith("=?gbk")) {
      BASE64Decoder decoder = new BASE64Decoder();
      try {
        return new String(decoder.decodeBuffer(str.substring(8, str.length()-2)), "GBK");
      } catch (IOException e) {
        e.printStackTrace();
        return str;
      }
    }else {
      return toChinese(str);
    }
  }
  
  public static String getFrom(String str) {
    if(str == null || str.length() == 0) {
      return str;
    }
    if(str.startsWith("=?GB") || str.startsWith("=?gb")) {
      try {
        return MimeUtility.decodeText(str);
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return str;
      }
    }else {
      return toChinese(str);
    }
  }
  
  public static String toChinese(String str) {
    if(str == null || str.length() == 0) {
      return str;
    }
    try {
      return new String(str.getBytes("ISO8859-1"), "GBK");
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
      return str;
    }
  }
}
